# coding:utf-8
# auth:yimin.tan@foxmail.com

import hashlib

def hash_passwd(passwd):
	solt="jfedu"
	fullpasswd=solt+passwd
	md5 = hashlib.md5(fullpasswd.encode(encoding='gb2312'))
	md5passwd = md5.hexdigest()[:40]
	return md5passwd

def get_userinfo(filename="passwd"):
	userinfo = {}
	try:
		with open(filename) as file:
			for i in file:
				array=i.strip("\n").split(":")
				username=array[0]
				password=array[1]
				if username.startswith("#"):
					pass
				else:
					userinfo[username]=password
			return userinfo
	except IOError as error:
		print("can read file,maybe file does not exits")

def write_userinfo(username,passwd,filename="passwd"):
	try:
		with open(filename,'a') as file:
			str=username+":"+hash_passwd(passwd)+"\n"
			file.write(str)
	except IOError as error:
		print("can read file,maybe file does not exits")

def register():
	username=str(input("请输入您要注册的用户名："))
	result=check_username(username)
	if result == "notin":
		passwd=str(input("请设置您的登录密码："))
		write_userinfo(username,passwd)
		print("注册成功，请前往登录")
		prove_main()
	else:
		choose=str(input("用户名%s已经被注册啦，请前往登录或者重新输入用户名[1:重新输入用户名 2:登录]")% username)
		if choose == "1":
			register()
		elif choose == "2":
			login()
		else:
			print("输入错误，退出系统。")

def login(times=0):
	username=str(input("请输入您的登录用户名："))
	result=check_username(username)
	if result == "in":
		passwd=str(input("请输入用户密码："))
		md5passwd=hash_passwd(passwd)
		userinfo=get_userinfo()
		if userinfo[username] == md5passwd:
			print("登录成功。祝您生活愉快。")
		else:
			if times < 3:
				print("密码错误，请重新输入。")
				times+=1
				login(times)
			else:
				print("错误次数过多，退出系统。")
	elif result == "notin":
		choose=str(input("用户名输入错误，可能您还没有注册，请选择[1:注册 2:重新输入]"))
		if choose == "1":
			register()
		elif choose == "2":
			login()
		else:
			print("输入错误，退出系统。")

def check_username(username):
	userinfo=get_userinfo()
	if username in userinfo:
		return "in"
	else:
		return "notin"

def prove_main(try_times=0):
	choose=str(input("欢迎来到京峰教育，请选择[1:注册 2:登录]:"))
	if choose == "1":
		register()
	elif choose == "2":
		login()
	else:
		if try_times <= 3:
			print("错误的输入,请输入1或者2.")
			try_times += 1
			prove_main(try_times)
		else:
			print("再见.")
			return 0


if __name__ == '__main__':
	prove_main()
